package cn.piesat.controller;


import cn.piesat.dto.MailmsgConfigDTO;
import cn.piesat.service.intf.MailmsgConfigService;
import cn.piesat.util.ResponseWrapperUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 手机短信和邮件的配置相关接口	控制层
 * @author 奚好雷
 *
 */
@RestController
@RequestMapping("/manager/mailmsg")
public class MailmsgConfigController {

	@Autowired
	private MailmsgConfigService service;
	
	/**
	 * 	添加短信配置信息，启用默认为未启用1
	 * @param json
	 * {
	 * 		"domain":"",	地址
	 * 		"accessKeyId":"",	用户标识
	 * 		"accessSecret":"",	用户秘钥
	 * 		"signName":"",	签名名称
	 * 		"template":{	模板
	 * 			"login":"",
	 * 			"register":"",
	 * 			"updatePassword":""
	 * 		},
	 * 		"platFormType":""  平台类型 aliyun/tencentyun
	 * }
	 * @return
	 */
	@PostMapping("/sms/add")
	public String addSmsMessage(@RequestBody String json) {
		MailmsgConfigDTO mailmsgConfigDTO = JSON.parseObject(json, MailmsgConfigDTO.class);
		mailmsgConfigDTO.setConfigType("sms");
		mailmsgConfigDTO.setEnableState(1);
		try {
			List<MailmsgConfigDTO> dtos = service.findByConfigTypeAndPlatFormType(mailmsgConfigDTO.getConfigType(), mailmsgConfigDTO.getPlatFormType());
			if(!dtos.isEmpty()) {
				return ResponseWrapperUtil.executeCustomTips("false", "该平台配置已存在,不允许重复添加");
			}
			service.addSmsMessage(mailmsgConfigDTO);
		} catch (Exception e) {
			return ResponseWrapperUtil.executeCustomTips("false", "添加发生错误");
		}
		return ResponseWrapperUtil.executeCustomTips("true", "添加成功");
	}
	
	/**
	 * 	修改短信配置信息
	 * @param json
	 * {	
	 * 		"id":"",
	 * 		"enableState":0 启用 1 禁用
	 * 		"domain":"",	地址
	 * 		"accessKeyId":"",	用户标识
	 * 		"accessSecret":"",	用户秘钥
	 * 		"signName":"",	签名名称
	 * 		"template":{	模板
	 * 			"login":"",
	 * 			"register":"",
	 * 			"updatePassword":""
	 * 		},
	 * 		"platFormType":""  平台类型 aliyun/tencentyun
	 * }
	 * @return
	 */
	@PostMapping("/sms/update")
	public String updateSmsMessage(@RequestBody String json) {
		MailmsgConfigDTO mailmsgConfigDTO = JSON.parseObject(json, MailmsgConfigDTO.class);
		//查询要修改的信息是否存在
		if (!service.exists(mailmsgConfigDTO.getId())) {
			return ResponseWrapperUtil.executeCustomTips("false", "该配置信息不存在，无法修改");
		}
		try {
			service.updateSmsMessage(mailmsgConfigDTO);
		} catch (Exception e) {
			return ResponseWrapperUtil.executeCustomTips("false", "修改失败");
		}
		return ResponseWrapperUtil.executeCustomTips("true", "修改成功");
	}
	
	/**
	 * 	修改短信启用状态
	 * @param json
	 *	{
	 *		"id":"",
	 *		"enableState":0 启用/ 1 禁用
	 *	}
	 * @return
	 */
	@PostMapping("/update/sms/state")
	public String updateSmsState(@RequestBody String json) {
		JSONObject jsonObject = JSON.parseObject(json);
		String id = jsonObject.getString("id");
		Integer state = jsonObject.getInteger("state");
		if (state == 0) {
			List<MailmsgConfigDTO> list = service.getTypeAndStateMessage("sms", 0);
			if(!list.isEmpty() && !list.get(0).getId().equals(id)) {
				return ResponseWrapperUtil.executeCustomTips("false", "已存在启用的手机短信配置内容");
			}
		}
		MailmsgConfigDTO findDTO = service.findById(id);
		if (findDTO == null) {
			return ResponseWrapperUtil.executeCustomTips("false", "该信息不存在");
		}
		findDTO.setEnableState(state);
		try {
			service.updateSmsMessage(findDTO);
		} catch (Exception e) {
			return ResponseWrapperUtil.executeCustomTips("false", "修改失败");
		}
		return ResponseWrapperUtil.executeCustomTips("true", "修改成功");
	}
	
	/**
	 * 	添加邮箱配置基本信息（启用状态默认为禁用）
	 * @param json
	 * {
	 * 		"domain":"",	地址
	 *		"username":"",   用户名
	 *      "password":"",		密码
	 * 		"signName":"",	主题
	 * 		"template":{	模板
	 * 			"login":"",
	 * 			"register":"",
	 * 			"updatePassword":""
	 * 		},
	 *      "platFormType":""  平台类型 163,qq
	 * }
	 * @return
	 */
	@PostMapping("/email/add")
	public String addEmailMessage(@RequestBody String json) {
		MailmsgConfigDTO mailmsgConfigDTO = JSON.parseObject(json, MailmsgConfigDTO.class);
		mailmsgConfigDTO.setConfigType("mail");
		mailmsgConfigDTO.setEnableState(1);
		try {
			List<MailmsgConfigDTO> dtos = service.findByConfigTypeAndPlatFormType(mailmsgConfigDTO.getConfigType(), mailmsgConfigDTO.getPlatFormType());
			if(!dtos.isEmpty()) {
				return ResponseWrapperUtil.executeCustomTips("false", "该平台配置已存在,不允许重复添加");
			}
			service.addEmailMessage(mailmsgConfigDTO);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseWrapperUtil.executeCustomTips("false", "保存发生错误");
		}
		return ResponseWrapperUtil.executeCustomTips("true", "保存成功");
	}
	
	/**
	 * 	修改邮箱信息
	 * @param json
	 * {	
	 * 		"id":"",
	 * 		"enableState": 0 启用 1 禁用
	 * 		"domain":"",	地址
	 *		"username":"",   用户名
	 *      "password":"",		密码
	 * 		"signName":"",	主题
	 * 		"template":{	模板
	 * 			"login":"",
	 * 			"register":"",
	 * 			"updatePassword":""
	 * 		},
	 *      "platFormType":""  平台类型 163,qq
	 * }
	 * @return
	 */
	@PostMapping("/email/update")
	public String updateEmailMessage(@RequestBody String json) {
		MailmsgConfigDTO mailmsgConfigDTO = JSON.parseObject(json, MailmsgConfigDTO.class);
		//查询是否存在要修改的信息
		if(!service.exists(mailmsgConfigDTO.getId())) {
			return ResponseWrapperUtil.executeCustomTips("false", "该配置信息不存在，无法修改");
		}
		try {
			service.updateEmailMessage(mailmsgConfigDTO);
		} catch (Exception e) {
			return ResponseWrapperUtil.executeCustomTips("false", "修改失败");
		}
		return ResponseWrapperUtil.executeCustomTips("true", "修改成功");
	}
	
	/**
	 * 	修改邮箱启用状态
	 * @param json
	 *	{
	 *		"id":"",
	 *		"enableState":0 启用/ 1 禁用
	 *	}
	 * @return
	 */
	@PostMapping("/update/mail/state")
	public String updateMailState(@RequestBody String json) {
		JSONObject jsonObject = JSON.parseObject(json);
		String id = jsonObject.getString("id");
		Integer state = jsonObject.getInteger("state");
		if (state == 0) {
			List<MailmsgConfigDTO> list = service.getTypeAndStateMessage("mail", 0);
			if(!list.isEmpty() && !list.get(0).getId().equals(id)) {
				return ResponseWrapperUtil.executeCustomTips("false", "已存在启用的邮箱配置内容");
			}
		}
		MailmsgConfigDTO findDTO = service.findById(id);
		if (findDTO == null) {
			return ResponseWrapperUtil.executeCustomTips("false", "该信息不存在");
		}
		findDTO.setEnableState(state);
		try {
			service.updateEmailMessage(findDTO);
		} catch (Exception e) {
			return ResponseWrapperUtil.executeCustomTips("false", "修改失败");
		}
		return ResponseWrapperUtil.executeCustomTips("true", "修改成功");
	}
	
	/**
	 * 	获取不同配置类型的所有信息  sms mail
	 * configType : 邮箱mail  手机 sms
	 * page : 页数
	 * size : 每页数据数量
	 */
	@GetMapping("/getAll/{configType}/{page}/{size}")
	public String getAllMessage(@PathVariable("configType")String configType,
								@PathVariable("page")Integer page,
								@PathVariable("size")Integer size) {
		if (page < 0) {
			page = 0;
		}
		if (size <= 0) {
			size = 8;
		}
		Map<String, Object> resultMap = service.getAllMessage(configType,page,size);
		List<Map<String, Object>> resultList = new ArrayList<>();
		Map<String, Object> map = null;
		List<MailmsgConfigDTO> list = (List<MailmsgConfigDTO>)resultMap.get("pageResultList");
		if (!list.isEmpty()) {
			for(MailmsgConfigDTO dto : list) {
				map = new HashMap<>();
				if (StringUtils.isNotBlank(dto.getAccessKeyId())) {
					map.put("accessKeyId", dto.getAccessKeyId());
				}
				if (StringUtils.isNotBlank(dto.getAccessSecret())) {
					map.put("accessSecret", dto.getAccessSecret());
				}
				if (StringUtils.isNotBlank(dto.getUsername())) {
					map.put("username", dto.getUsername());
				}
				if (StringUtils.isNotBlank(dto.getPassword())) {
					map.put("password", dto.getPassword());
				}
				if (StringUtils.isNotBlank(dto.getPlatFormType())) {
					map.put("platFormType", dto.getPlatFormType());
				}
				map.put("id", dto.getId());
				map.put("configType", dto.getConfigType());
				map.put("enableState", dto.getEnableState());
				map.put("signName", dto.getSignName());
				map.put("domain", dto.getDomain());
				Map<String, String> tempMap = JSON.parseObject(dto.getTemplate(), new TypeReference<Map<String, String>>(){});
				map.put("template", tempMap);
				resultList.add(map);
			}
			resultMap.put("pageResultList", resultList);
		}
		return ResponseWrapperUtil.executeResultMap(resultMap);
	}
	
	/**
	 *	删除信息 
	 * @param id	
	 * @return
	 */
	@DeleteMapping("/del/{id}")
	public String delMessage(@PathVariable("id")String id) {
		try {
			service.delById(id);
		} catch (Exception e) {
			return ResponseWrapperUtil.executeCustomTips("false", "删除失败");
		}
		return ResponseWrapperUtil.executeCustomTips("true", "删除成功");
	}
	
	/**
	 * 	根据ID查询数据
	 * @param id
	 * @return
	 */
	@GetMapping("/get/{id}")
	public String findById(@PathVariable("id")String id) {
		MailmsgConfigDTO dto = service.findById(id);
		if (dto == null) {
			return ResponseWrapperUtil.executeCustomTips("false", "该信息不存在");
		}
		Map<String, Object> map = new HashMap<>();
		if (StringUtils.isNotBlank(dto.getAccessKeyId())) {
			map.put("accessKeyId", dto.getAccessKeyId());
		}
		if (StringUtils.isNotBlank(dto.getAccessSecret())) {
			map.put("accessSecret", dto.getAccessSecret());
		}
		if (StringUtils.isNotBlank(dto.getUsername())) {
			map.put("username", dto.getUsername());
		}
		if (StringUtils.isNotBlank(dto.getPassword())) {
			map.put("password", dto.getPassword());
		}
		if (StringUtils.isNotBlank(dto.getPlatFormType())) {
			map.put("platFormType", dto.getPlatFormType());
		}
		map.put("id", dto.getId());
		map.put("configType", dto.getConfigType());
		map.put("enableState", dto.getEnableState());
		map.put("signName", dto.getSignName());
		map.put("domain", dto.getDomain());
		Map<String, String> tempMap = JSON.parseObject(dto.getTemplate(), new TypeReference<Map<String, String>>(){});
		map.put("template", tempMap);
		return ResponseWrapperUtil.executeResultMap(map);
	}
}
